package luo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @author luo
 */
public class NettyClient {

    public static void main(String[] args) {
        // 创建连接池对象
        NioEventLoopGroup group = new NioEventLoopGroup();

        // 启动引导类
        Bootstrap bootstrap = new Bootstrap();

        // 配置启动引导类
        bootstrap
                .group(group)
                // 通道
                .channel(NioSocketChannel.class)
                // 设置 channel 初始化监听
                .handler(new ChannelInitializer<Channel>() {
                    // 监听 channel 是否初始化
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        // 设置编码
                        channel.pipeline().addLast(new StringEncoder());
                    }
                });

        // 使用启动引导类连接服务端, 获取一个channel
        ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8081);
        Channel channel = channelFuture.channel();

        // 写数据到服务端
        Scanner scanner = new Scanner(System.in);
        while (true) {
            String str = scanner.nextLine();
            channel.writeAndFlush(str);
        }

    }

}
